// index.js
// 获取应用实例
const app = getApp()

Page({
  data: {
    list: [],
    food: '今天吃什么',
    iTimer: '',
    oTimer: '',
    sTimer: '',
    second: 2,
    bgColor: '',
    isPig: false
  },
  // 转发页面
  onShareAppMessage(){
    return{
      title:'今天也有好好吃饭'
    }
  },
  // 分享到朋友圈，只在安卓中支持
  onShareTimeline(){
    return{
      title:'今天也有好好吃饭'
    }
  },
  // 抽取
  start() {
    // 倒计时
    const second = wx.getStorageSync('second')
    if (second) this.setData({ second })
    let newSecond = second || this.data.second
    this.setData({ second: --newSecond })
    clearInterval(this.data.iTimer)
    clearInterval(this.data.oTimer)
    clearInterval(this.data.sTimer)
    this.setData({ isPig: true })

    this.data.iTimer = setInterval(() => {
      const num = Math.floor(Math.random() * this.data.list.length)
      this.setData({ food: this.data.list[num] })
    }, 50)

    this.data.sTimer = setInterval(() => {
      this.setData({ second: --newSecond })
      if (newSecond < 0) {
        clearInterval(this.data.sTimer)
        let second = wx.getStorageSync('second')
        if (second) this.setData({ second })
      }
    }, 1000)

    this.data.oTimer = setTimeout(() => {
      clearInterval(this.data.iTimer)
      this.setData({ isPig: false })
    }, this.data.second * 1000)
  },
  // 停止
  stop() {
    clearInterval(this.data.iTimer)
  },
  // 跳转设置
  bindViewTap() {
    wx.navigateTo({
      url: '../setting/setting'
    })
  },
  onLoad() {
    console.log("onLoad")
    // 设置默认菜单
    let list = wx.getStorageSync('foodList')
    if (!list || list.length == 0) {
      list = ['水饺', '牛肉面', '薯条', '汉堡', '螺蛳粉', '隆江猪脚饭', '脆皮鸡拌饭', '猪扒饭', '韩式炸鸡', '煲仔饭', '酱骨饭', '猪肚鸡汤饭', '江南小粥']
    }
    wx.setStorageSync('foodList', list)
    this.setData({ list })
  },
  edit() {
    app.globalData.second += 1
  },
  onShow() {
    let list = wx.getStorageSync('foodList')
    if (list) this.setData({ list })
    let second = wx.getStorageSync('second')
    if (second) this.setData({ second })
    let bgColor = wx.getStorageSync('bgColor')
    if (bgColor) this.setData({ bgColor })
    this.setData({ food: '今天吃什么' })
  },
  onHide() {
    // 清楚所有计时器
    clearInterval(this.data.iTimer)
    clearInterval(this.data.oTimer)
    clearInterval(this.data.sTimer)
    this.setData({ isPig: false })
  }
})


